package com.xm.concurrent.base;

import java.util.concurrent.TimeUnit;

/**
 * 4.3.6 ThreadLocal 的使用
 *
 * @author xiaoming
 * @date 2021-05-27 6:29
 */
public class ThreadLocalProfiler {
    private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>(){
        @Override
        protected Long initialValue() {
            return System.currentTimeMillis();
        }
    };
    public static final void begin() {
        TIME_THREADLOCAL.set(System.currentTimeMillis());
    }
    public static final long end() {
        return System.currentTimeMillis() - TIME_THREADLOCAL.get();
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(String.format("ThreadLocal init : %d", ThreadLocalProfiler.TIME_THREADLOCAL.get() ) );

        TimeUnit.SECONDS.sleep(1);

        ThreadLocalProfiler.begin();
        TimeUnit.SECONDS.sleep(1);
        System.out.println(String.format("Cost: %d mills", ThreadLocalProfiler.end()));
    }


}
